package com.site.user.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.site.data.JPABaseDAOImpl;
import com.site.user.pojo.TbGroup;
import com.site.user.pojo.TbRole;

import com.site.user.pojo.TbUser;

/**
 * @author      zhanjun
 * @date        2010-12-8
 * @version     1.0
 * @description 角色表服务层
 * 
 */
@Service("tbGroupService")
public class TbGroupService extends JPABaseDAOImpl<TbGroup> implements ITbGroupService {

	@Resource
	private ITbUserService tbUserService;

	@Override
	public List<Object[]> getUserSystem(TbUser instance) {// 得到用户的系统
		String treesql = "";
		List<Object[]> listsys = null;
		if (instance != null) {
			if ("99".equals(instance.getSign())) {// 99级用户可以看到全部的系统
				treesql = "select ID_RESOURCE,RES_NAME from TB_RESOURCE y where y.SIGN=1 and y.PARENT_ID=-1 order by ORDERBY ";
			} else {//其它级别的用户看自己分配的系统

				Object[] rid = tbUserService.getUserRolesId(instance);
				String rolesid = "'" + StringUtils.join(rid, "','") + "'";
				treesql = "select distinct vp.ID_RESOURCE,vp.RES_NAME" + " from V_PRIVIGE vp where vp.ID_ROLE in ("
						+ rolesid + ") and vp.PID=-1 order by vp.ID_RESOURCE";
			}

			listsys = jdbcExecQuery(treesql, null);
		}
		return listsys;
	}

	@Override
	public List<Object[]> getUserRole(TbUser instance, String idresouce) {// 得到用户某个系统的角色
		String treesql = "";
		List<Object[]> listsys = null;
		if ((instance != null) && (StringUtils.isNotEmpty(idresouce))) {
			if ("99".equals(instance.getSign())) {
				treesql = "select DISTINCT y.ID_ROLE,y.ROLE_NAME,y.ROLE_DESC from V_PRIVIGE y where y.ID_SYSTEM='"
						+ idresouce + "' order by y.ID_ROLE";
			} else {//其它级别的用户看自己分配的角色
				Object[] rid = tbUserService.getUserRolesId(instance);
				String rolesid = "'" + StringUtils.join(rid, "','") + "'";

				treesql = "select distinct vp.ID_ROLE,vp.ROLE_NAME,vp.ROLE_DESC"
						+ " from V_PRIVIGE vp where vp.ID_ROLE in (" + rolesid + ") and vp.ID_SYSTEM='" + idresouce
						+ "' order by vp.ID_ROLE";
			}
			listsys = jdbcExecQuery(treesql, null);
		}
		return listsys;
	}

	@Override
	public String groupRoleSave(String idGroup, String idRole) {
		String msg = "ERROR";
		if ((StringUtils.isNotEmpty(idGroup)) && (StringUtils.isNotEmpty(idRole))) {
			String[] roles = idRole.split(",");
			String insert = "INSERT INTO tb_grou_role (ID_GROUP,ID_ROLE) VALUES";
			List<String> sqlvalue = new ArrayList<String>();
			if (roles != null) {
				for (int i = 0; i < roles.length; i++) {
					String roleid = roles[i];
					if (StringUtils.isNotEmpty(roleid)) {
						String testsql = "SELECT COUNT(ID_GROUP) FROM tb_grou_role WHERE ID_GROUP='" + idGroup
								+ "' AND ID_ROLE='" + roleid + "' ";
						List count = jdbcExecQuery(testsql, null);
						Object resobj = (Object) count.get(0);
						if ("0".equals(resobj.toString())) {//判断不重复
							StringBuilder sql = new StringBuilder();
							sql.append("(");
							sql.append("'");
							sql.append(idGroup);
							sql.append("','");
							sql.append(roleid);
							sql.append("'");
							sql.append(")");
							sqlvalue.add(sql.toString());
						}
					}
				}
			}
			if (sqlvalue.size() > 0) {
				String insql = insert + StringUtils.join(sqlvalue, ",");
				jdbcExecUpdate(insql);
				msg = "保存成功";
			}
		}
		return msg;
	}

	@Override
	public List<TbGroup> getGroupList(TbUser instance) {
		String sql = "";
		if (instance != null) {
			Set<TbGroup> tgSet = null;
			if ("99".equals(instance.getSign())) {// 99级用户可以看到全部的组
				sql = "SELECT c FROM TbGroup c WHERE c.sign=1 ORDER BY c.groupType asc,c.createdTime DESC";
				List<TbGroup> list = queryForList(sql, TbGroup.class);
				return list;

			} else {//其它级别的用户看自己分配的系统
				tgSet = instance.getTbGroupSet();
				sql = "SELECT c FROM TbGroup c WHERE c.sign=1 and c.groupType='1' ORDER BY c.createdTime DESC";
				List<TbGroup> list = queryForList(sql, TbGroup.class);

				if ((tgSet != null) && (list != null)) {
					for (TbGroup group : list) {
						tgSet.add(group);//去重复的记录
					}
					List<TbGroup> tglist =new ArrayList<TbGroup>();
					
					Collections.sort(tglist,new Comparator<TbGroup>() {	
						@Override
						public int compare(TbGroup c, TbGroup arg1) {
							return c.getGroupType().compareTo(arg1.getGroupType());		//按类别排序					
						}
					});
					return tglist;
					
				}
				
			}

		}
		return null;
	}

	@Override
	public Set<TbRole> getGroupRoles(String idGroups) {
		if(StringUtils.isEmpty(idGroups)){
			return null;			
		}
		Set<TbRole> roleSet=new HashSet<TbRole>();
		String[] ids=null;
		if(StringUtils.indexOf(idGroups, ",")!=-1){
			ids=StringUtils.split(idGroups);
		}else{
			ids=new String[]{idGroups};
		}
		
		if(ids!=null){
			for(String id:ids){
				TbGroup group=execFindById(id);
				Set<TbRole> role=group.getTbRoleSet();
				roleSet.addAll(role);
			}
		}		
		return roleSet;
	}

}
